package com.smarth.zhizulian.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.smarth.zhizulian.R;
import com.smarth.zhizulian.activity.AgentWebActivity;
import com.smarth.zhizulian.activity.FriendsActivity;
import com.smarth.zhizulian.activity.HongBaoRainActivity;
import com.smarth.zhizulian.activity.LoginActivity;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.app.EventFragment;
import com.smarth.zhizulian.bean.BaseEntity;
import com.smarth.zhizulian.bean.lucky.LuckyInfo;
import com.smarth.zhizulian.bean.lucky.LuckyMyFriendLucky;
import com.smarth.zhizulian.bean.lucky.LuckyOpenFriendLucky;
import com.smarth.zhizulian.bean.user.DiscipleIndex;
import com.smarth.zhizulian.entity.EventBean;
import com.smarth.zhizulian.http.KumaHttp;
import com.smarth.zhizulian.http.observer.ProgressObserver;
import com.smarth.zhizulian.http.utils.RxCompos;
import com.smarth.zhizulian.popupwindow.FriendHongBaoDialog;
import com.smarth.zhizulian.utils.AutoUtils;
import com.smarth.zhizulian.utils.GlideUtils;
import com.smarth.zhizulian.utils.GsonUtils;
import com.smarth.zhizulian.utils.KumaDialogFactory;
import com.smarth.zhizulian.utils.KumaLog;
import com.smarth.zhizulian.utils.KumaToast;
import com.smarth.zhizulian.utils.ShareUtils;
import com.smarth.zhizulian.utils.TimeUtils;
import com.smarth.zhizulian.utils.UserUtils;
import com.smarth.zhizulian.utils.listhelper.RefreshHelper;
import com.smarth.zhizulian.utils.listhelper.impl.adapter.PageDataAdapter;
import com.smarth.zhizulian.utils.listhelper.impl.model.HttpPageDataModel;
import com.smarth.zhizulian.view.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.umeng.analytics.MobclickAgent;
import com.yqritc.recyclerviewflexibledivider.VerticalDividerItemDecoration;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 18865 on 2018/2/1.
 */

public class HongBaoFragment extends EventFragment {
    @BindView(R.id.rv_recyclerview)
    RecyclerView rvRecyclerview;
    @BindView(R.id.ll_loadinglayout)
    LoadingLayout llLoadinglayout;
    @BindView(R.id.tv_hongbao)
    TextView tvHongbao;
    @BindView(R.id.pb_health)
    ProgressBar pbHealth;
    @BindView(R.id.tv_health)
    TextView tvHealth;
    @BindView(R.id.tv_lefttime)
    TextView tvLefttime;
    @BindView(R.id.ll_left)
    LinearLayout llLeft;
    @BindView(R.id.ll_normal)
    LinearLayout llNormal;
    @BindView(R.id.ll_loadinglayout_friends)
    LoadingLayout llLoadinglayoutFriends;
    @BindView(R.id.rv_refresh)
    SmartRefreshLayout rvRefresh;
    @BindView(R.id.iv_bg)
    ImageView ivBg;
    @BindView(R.id.iv_active)
    ImageView ivActive;
    private BaseQuickAdapter<LuckyMyFriendLucky, BaseViewHolder> adapter;
    private RefreshHelper<LuckyInfo> refreshHelper;
    private PageDataAdapter<LuckyInfo> pageDataAdapter;
    private Disposable mDisposable;

//    private boolean canOpen;        //是否可拆

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        super.onCreateView(savedInstanceState);
        setBKView(R.layout.fragment_hongbao);
        AutoUtils.auto(contentView);
        initFriendHongBao();
        initHongBao();
        startCountDown();
    }

    private void initHongBao() {
        if (UserUtils.isLogin()) {
            refreshHelper = new RefreshHelper<>(mContext, llLoadinglayout, rvRefresh);
            refreshHelper.setDataModel(new HttpPageDataModel<LuckyInfo>(mContext) {
                @Override
                public Observable<LuckyInfo> getObservable() {
                    return KumaHttp.getService().luckyInfo().compose(RxCompos.<LuckyInfo>getBELoginCompos())
                            .doOnSubscribe(new Consumer<Disposable>() {
                                @Override
                                public void accept(Disposable disposable) throws Exception {
                                    if (mDisposable != null && !mDisposable.isDisposed()) {
                                        KumaLog.kuma("mDisposable");
                                        mDisposable.dispose();
                                    }
                                    fetchFriends();
                                }
                            });
                }
            });
            pageDataAdapter = new PageDataAdapter<LuckyInfo>() {
                @Override
                public void onGetData(final LuckyInfo luckyInfo, boolean isRefresh) {
                    super.onGetData(luckyInfo, isRefresh);
                    tvHongbao.setText(luckyInfo.getCoin() + "金币");
                    tvHealth.setText(luckyInfo.getEnergy() + "/50");
                    pbHealth.setProgress(luckyInfo.getEnergy());

                    if (luckyInfo.getIsLock() == 0) {
                        llNormal.setVisibility(View.VISIBLE);
//                        llLock.setVisibility(View.GONE);
                        ivBg.setSelected(false);
                        ivActive.setVisibility(View.GONE);
                        if (luckyInfo.getIsOpen() == 0) {
                            final long count = luckyInfo.getCountDown() / 1000l;
                            Observable.interval(0, 1, TimeUnit.SECONDS)
                                    .take(count + 1) //设置循环
                                    .map(new Function<Long, Long>() {
                                        @Override
                                        public Long apply(@NonNull Long aLong) throws Exception {
                                            return luckyInfo.getCountDown() - (aLong * 1000); //
                                        }
                                    })
                                    .doOnSubscribe(new Consumer<Disposable>() {
                                        @Override
                                        public void accept(Disposable disposable) throws Exception {
//                                    tv_lefttime.setVisibility(View.VISIBLE);
                                            llLeft.setVisibility(View.VISIBLE);
//                                            canOpen = false;
                                        }
                                    })
                                    .observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI线程
                                    .subscribe(new Observer<Long>() {
                                        @Override
                                        public void onSubscribe(@NonNull Disposable d) {
                                            mDisposable = d;
                                        }

                                        @Override
                                        public void onNext(@NonNull Long aLong) {
                                            tvLefttime.setText(TimeUtils.getHongBaoLeftTime(aLong));
                                        }

                                        @Override
                                        public void onError(@NonNull Throwable e) {
                                            e.printStackTrace();
                                            KumaToast.showError(mContext, e.getMessage());
                                        }

                                        @Override
                                        public void onComplete() {
                                            llLeft.setVisibility(View.GONE);
                                        }
                                    });
                        } else {
                            tvLefttime.setText(TimeUtils.getHongBaoLeftTime(0));
                            llLeft.setVisibility(View.GONE);
//                            canOpen = true;
                        }
                    } else {
                        llNormal.setVisibility(View.GONE);
//                        llLock.setVisibility(View.VISIBLE);
                        ivBg.setSelected(true);
                        ivActive.setVisibility(View.VISIBLE);
                    }
                }
            };
            refreshHelper.setDataAdapter(pageDataAdapter);
            refreshHelper.refresh();
        } else {
            llLeft.setVisibility(View.GONE);
        }
    }

    private void fetchFriends() {
        if (UserUtils.isLogin()) {
            KumaHttp.getService().luckyMyFriendLucky()
                    .compose(RxCompos.<List<LuckyMyFriendLucky>>getBELoginCompos())
                    .subscribe(new ProgressObserver<List<LuckyMyFriendLucky>>(mContext, false) {
                        @Override
                        public void onNext(List<LuckyMyFriendLucky> luckyMyFriendLuckyList) {
                            adapter.setNewData(luckyMyFriendLuckyList);
                            if (luckyMyFriendLuckyList != null && luckyMyFriendLuckyList.size() == 0) {
                                llLoadinglayoutFriends.showEmpty();
                            } else {
                                llLoadinglayoutFriends.showContent();
                            }
                        }

                        @Override
                        public void onSubscribe(Disposable d) {
                            super.onSubscribe(d);
                            llLoadinglayoutFriends.showLoading();
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            llLoadinglayoutFriends.showError();
                        }
                    });
        }
    }

    private void initFriendHongBao() {
        List<LuckyMyFriendLucky> list = new ArrayList<>();
        adapter = new BaseQuickAdapter<LuckyMyFriendLucky, BaseViewHolder>(R.layout.item_friendhongbao, list) {

            @Override
            protected void convert(BaseViewHolder helper, LuckyMyFriendLucky item) {
                GlideUtils.loadAvatar(mContext, item.getAvatar(), (ImageView) helper.getView(R.id.iv_avatar));
                helper.setText(R.id.tv_name, item.getNickname());
                helper.setText(R.id.tv_time, TimeUtils.getFriendHongBaoTime(item.getCountDown()));
            }

            @Override
            protected BaseViewHolder createBaseViewHolder(View view) {
                AutoUtils.auto(view);
                return super.createBaseViewHolder(view);
            }
        };
        rvRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        rvRecyclerview.addItemDecoration(new VerticalDividerItemDecoration.Builder(mContext).color(Color.TRANSPARENT).size(DensityUtil.dp2px(27.44f)).build());
        adapter.bindToRecyclerView(rvRecyclerview);
        llLoadinglayoutFriends.setOnRetryEmptyClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserUtils.isLogin()) {
                    LoginActivity.open(mContext);
                } else {
                    addFriend();
                }
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                KumaHttp.getService().luckyOpenFriendLucky(((LuckyMyFriendLucky) adapter.getItem(position)).getFriendId())
                        .compose(RxCompos.getBEAll2LoginCompos())
//                        .subscribe(new ProgressObserver<LuckyOpenFriendLucky>(mContext) {
//                            @Override
//                            public void onNext(LuckyOpenFriendLucky luckyOpenFriendLucky) {
//                                KumaDialogFactory.buildLeftHongBaoDialog(getActivity(), luckyOpenFriendLucky.getCoin(), luckyOpenFriendLucky.getId()).show();
//                                EventBus.getDefault().post(new EventBean(BaseConfig.EventCode.REFRESH_HONGBAO, "HongBaoFragment"), "HongBaoFragment");
//                            }
//                        });
                        .subscribe(new ProgressObserver<BaseEntity>(mContext) {
                            @Override
                            public void onNext(BaseEntity baseEntity) {
//                                LuckyOpenFriendLucky luckyOpenFriendLucky = (LuckyOpenFriendLucky) baseEntity.getData();
//                                Map<String, String> map = (Map<String, String>) baseEntity.getData();
                                LuckyOpenFriendLucky luckyOpenFriendLucky = GsonUtils.fromJson(GsonUtils.toJson(baseEntity.getData()), LuckyOpenFriendLucky.class);
//                                KumaDialogFactory.buildLeftHongBaoDialog(getActivity(), luckyOpenFriendLucky.getCoin(), luckyOpenFriendLucky.getId()).show();
                                new FriendHongBaoDialog(getActivity(), luckyOpenFriendLucky.getCoin(), luckyOpenFriendLucky.getId()).show();
                                EventBus.getDefault().post(new EventBean(BaseConfig.EventCode.REFRESH_HONGBAO, "HongBaoFragment"), "HongBaoFragment");
                            }

                            @Override
                            public void onErrorApi(BaseEntity be) {
                                if (BaseConfig.NetWork.CODE_TOKENEXPIRED.equals(be.getCode())) {
                                    EventBus.getDefault().post(new EventBean(be.getMessage()), BaseConfig.EventTag.RELOGIN);
                                } else if (BaseConfig.ApiCode.LUCKY_ENERTY.equals(be.getCode())) {
                                    KumaDialogFactory.buildNoHealth(getActivity(), Double.valueOf(be.getData().toString()).intValue()).show();
                                } else {
                                    KumaToast.show(mOContext, be.getMessage());
                                }
                            }
                        });
            }
        });
//        fetchFriends();
    }

    @OnClick({R.id.iv_open, R.id.iv_hongbao, R.id.iv_active, R.id.iv_addfriend, R.id.tv_rule, R.id.tv_myfriends})
    public void onViewClicked(View view) {
        if (!UserUtils.isLogin() && view.getId() != R.id.tv_rule) {
            LoginActivity.open(mContext);
            return;
        }
        switch (view.getId()) {
            case R.id.iv_addfriend:
                addFriend();
//                KumaDialogFactory.buildLeftHongBaoDialog(getActivity(), 1000, 2).show();
                break;
            case R.id.iv_open:
                KumaHttp.getService().luckyOpenPack()
                        .compose(RxCompos.<Integer>getBEAll2LoginCompos())
                        .subscribe(new ProgressObserver<BaseEntity>(mContext) {
                            @Override
                            public void onNext(BaseEntity baseEntity) {
                                KumaDialogFactory.buildHongBaoRainStartDialog(getActivity(), new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        HongBaoRainActivity.open(mContext);
                                    }
                                }).show();
                            }

                            @Override
                            public void onErrorApi(BaseEntity be) {
                                if (BaseConfig.NetWork.CODE_TOKENEXPIRED.equals(be.getCode())) {
                                    EventBus.getDefault().post(new EventBean(be.getMessage()), BaseConfig.EventTag.RELOGIN);
                                } else if (BaseConfig.ApiCode.LUCKY_ENERTY.equals(be.getCode())) {
                                    KumaDialogFactory.buildNoHealth(getActivity(), (int) be.getData()).show();
                                } else {
                                    KumaToast.show(mOContext, be.getMessage());
                                }
                            }
                        });
                break;
            case R.id.iv_hongbao:
                break;
            case R.id.iv_active:
                EventBus.getDefault().post(new EventBean(BaseConfig.EventCode.SHOW_ARTICLE, "HongBaoFragment"), "MainActivity");
                break;
            case R.id.tv_rule:
                AgentWebActivity.openForHongBaoRule(mContext);
                break;
            case R.id.tv_myfriends:
                FriendsActivity.open(mContext);
                break;
        }
    }

    @Override
    public void onDestroyView() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            KumaLog.kuma("mDisposable");
            mDisposable.dispose();
        }
        super.onDestroyView();
    }

    @Subscriber(tag = "HongBaoFragment")
    private void onEvent(EventBean eb) {
        switch (eb.getCode()) {
            case BaseConfig.EventCode.ON_FINISH_HONGBAORAIN:
                refreshHelper.refresh();
                final int count = (int) eb.getBody();
                KumaHttp.getService().luckyOpenPackEnd(count)
                        .compose(RxCompos.<Integer>getBELoginCompos())
                        .subscribe(new ProgressObserver<Integer>(mContext) {
                            @Override
                            public void onNext(Integer integer) {
                                KumaDialogFactory.buildGetHongBaoRainDialog(getActivity(), "" + count, "" + integer).show();
                            }
                        });
                break;
            case BaseConfig.EventCode.REFRESH_HONGBAO:
                refreshHelper.refresh();
                break;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && UserUtils.isLogin() && refreshHelper != null) {
            refreshHelper.refresh();
        }
    }

    private void addFriend() {
        KumaHttp.getService().discipleIndex()
                .compose(RxCompos.<DiscipleIndex>getBELoginCompos())
                .subscribe(new ProgressObserver<DiscipleIndex>(mContext) {
                    @Override
                    public void onNext(final DiscipleIndex discipleIndex) {
                        KumaDialogFactory.buildShareDialog(getActivity(), new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ShareUtils.shareForAddFriends(getActivity(), discipleIndex, Wechat.NAME);
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ShareUtils.shareForAddFriends(getActivity(), discipleIndex, WechatMoments.NAME);
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ShareUtils.shareForAddFriends(getActivity(), discipleIndex, QQ.NAME);
                            }
                        }).show();
                    }
                });
    }

    @Override
    protected void onLogin(EventBean eb) {
        super.onLogin(eb);
        initHongBao();
    }

    private void startCountDown() {
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (adapter.getData() != null && adapter.getData().size() > 0) {
                            List<LuckyMyFriendLucky> data = adapter.getData();
                            Iterator<LuckyMyFriendLucky> it = data.iterator();
                            while (it.hasNext()) {
                                LuckyMyFriendLucky temp = it.next();
                                long tempTime = temp.getCountDown() - 1 * 1000;
                                if (tempTime >= 0) {
                                    temp.setCountDown(tempTime);
                                } else {
                                    temp.setCountDown(0);
                                    it.remove();
                                }
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("HongBaoFragment");
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("HongBaoFragment");
    }
}
